/**
 * 
 */
package com.df.tv.launcher.fragment;

import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.support.v4.view.ViewPager.PageTransformer;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver.OnGlobalFocusChangeListener;

import com.df.tv.launcher.LauncherApplication;
import com.df.tv.launcher.R;
import com.df.tv.launcher.entity.FileInfo;
import com.df.tv.launcher.entity.MarqueeMsgInfo;
import com.df.tv.launcher.model.RecommendDataParser;
import com.df.tv.launcher.params.AppTest;
import com.df.tv.launcher.params.ComParams;
import com.df.tv.launcher.util.FileAccess;
import com.df.tv.launcher.util.JsonParseUtil;
import com.df.tv.launcher.util.TmsGetFileTask;
import com.df.tv.launcher.util.TmsGetFileTask.onTmsGetFile;
import com.df.tv.launcher.util.XHttpParamsUtil;
import com.df.tv.launcher.view.DynaPointsView;
import com.df.tv.launcher.view.MarqueeTextView;
import com.df.tv.launcher.view.Preview;
import com.df.tv.launcher.view.SwitchView;
import com.df.tv.launcher.view.VideoPlayerView;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonSyntaxException;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.telecom.tv189.comlib.dynamicui.AttributeKey;
import com.telecom.tv189.comlib.dynamicui.LayoutInflater.DefaultViewLoader;
import com.telecom.tv189.comlib.dynamicui.UIGenerator;
import com.telecom.tv189.comlib.dynamicui.view.FrameLayout;
import com.telecom.tv189.comlib.net.XHttpClient;
import com.telecom.tv189.comlib.net.json.entity.BaseEntity;
import com.telecom.tv189.comlib.util.Attributes;
import com.telecom.tv189.comlib.util.Log;
import com.telecom.tv189.comlib.view.CycleViewPager;
import com.telecom.tv189.comlib.view.FocusAmplifier;
import com.telecom.tv189.comlib.view.FocusAmplifier.AmplifyListener;
import com.telecom.tv189.comlib.view.ScaleViewFocusAmplifier;
import com.telecom.tv189.silentlogin.UserInfo;
import com.telecom.tv189.silentlogin.UserInfoKeeper;

/**
 */
public class HomeViewPagerFragment extends Fragment {

    private static final String TAG = "HomeViewPagerFragment";

    private static final int SCROLL_MSG_FILE = 7;

    public static final int WIDTH_OFFSET = 140;
    public static final int HEIGHT_OFFSET = 40;

    public static final int PAGE_WIDTH = 1000 + WIDTH_OFFSET * 2;
    public static final int PAGE_HEIGHT = 420 + HEIGHT_OFFSET * 2;
    public static final int PAGE_STEP = 1040;
    public static final int PAGE_VERTICAL_GRAVITY = Gravity.TOP;

    public static final int FOUCS_BIG_AREA = 10000;

    private Activity _activity;
    private UIGenerator uIGenerator;
    private CycleViewPager contentPager_flyt;
    private DynaPointsView pagePointer;
    private ScaleViewFocusAmplifier focusAmplifier;
    private ExecutorService threadPool;
    private MarqueeTextView marqueeText;

    private Semaphore mutex;

    private Handler hander = new Handler();

    /*
     * (non-Javadoc)
     * 
     * @see android.support.v4.app.Fragment#onAttach(android.app.Activity)
     */
    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        _activity = activity;
        // TODO 获取主activity的引用;
        Log.d(TAG, "onAttach()");
    }

    /*
     * (non-Javadoc)
     * 
     * @see android.support.v4.app.Fragment#onCreate(android.os.Bundle)
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO　创建后台工作线程和任务
        Log.d(TAG, "onCreate()");

        DefaultViewLoader mLoader = new DefaultViewLoader();
        mLoader.addViewClass(VideoPlayerView.CLASS_PATTERN, VideoPlayerView.class, 0);
        mLoader.addViewClass(Preview.CLASS_PATTERN, Preview.class, 0);
        mLoader.addViewClass(SwitchView.CLASS_PATTERN, SwitchView.class, 0);
        mLoader.addViewClass(FrameLayout.CLASS_PATTERN, FrameLayout.class, 0);

        uIGenerator = new UIGenerator(_activity, new RecommendDataParser(), mLoader);
        threadPool = Executors.newSingleThreadExecutor();
        mutex = new Semaphore(1);
    }

    /*
     * (non-Javadoc)
     * 
     * @see android.support.v4.app.Fragment#onCreateView(android.view.LayoutInflater, android.view.ViewGroup,
     * android.os.Bundle)
     */
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        Log.d(TAG, "OnCreatView()");

        // TODO 创建自己的用户界面
        // 创建、填充Fragment的UI，并返回它，
        // 如果这个Fragment没有 UI，那么返回null
        View view = inflater.inflate(R.layout.fragment_home_view_pager, container, false);
        marqueeText = (MarqueeTextView) view.findViewById(R.id.marqueeeTextView);
        startScrollMessage();
        contentPager_flyt = (CycleViewPager) view.findViewById(R.id.contentPagerContainer);
        pagePointer = (DynaPointsView) view.findViewById(R.id.pagePointer);

        contentPager_flyt.setPageTransformer(new PageTransformer() {

            @Override
            public void transformPage(View page, float position) {
                // if (position < -1 || position > 1) {
                // return;
                // }
                page.setScaleX(1 - Math.abs(position) * 0.2f);
                page.setScaleY(1 - Math.abs(position) * 0.2f);
                page.setAlpha(1 - Math.abs(position) * 0.8f);
                page.setBackgroundColor(Color.TRANSPARENT);
                page.setTranslationX(position * -90);
            }
        });
        contentPager_flyt.setOnPageChangeListener(new OnPageChangeListener() {

            @Override
            public void onPageSelected(int arg0) {
                Log.d(TAG, "OnPageChangeListener(" + arg0 + ")");
                pagePointer.setPosition(arg0);

                ArrayList<View> subPages = contentPager_flyt.getPages();
                ArrayList<VideoPlayerView> videoViews = VideoPlayerView.getInstanceTags();
                if (subPages != null && subPages.size() > 0 && videoViews != null && videoViews.size() > 0) {
                    for (VideoPlayerView videView : videoViews) {
                        View parent = (View) videView.getParent();
                        if (!subPages.contains(parent))
                            continue;
                        if (parent == contentPager_flyt.getPageByIndex(arg0)) {
                            videView.play();
                        }
                        else {
                            videView.pause(true);
                        }
                    }
                }
            }

            @Override
            public void onPageScrolled(int arg0, float arg1, int arg2) {

            }

            @Override
            public void onPageScrollStateChanged(int arg0) {

            }
        });

        contentPager_flyt.setPageWidth(PAGE_WIDTH);
        contentPager_flyt.setPageHeight(PAGE_HEIGHT);
        contentPager_flyt.setPageStep(PAGE_STEP);
        contentPager_flyt.setVerticalGravity(PAGE_VERTICAL_GRAVITY);
        focusAmplifier = new ScaleViewFocusAmplifier(getActivity(), contentPager_flyt);
        focusAmplifier.setZoomer(new FocusAmplifier.FixAreaZoomer(FOUCS_BIG_AREA));
        focusAmplifier.setAmplifyListener(new AmplifyListener() {

            @Override
            public void OnZoomedOut(View view) {
                Log.d(TAG, "video zoom out");
                if (view instanceof VideoPlayerView) {
                    ((VideoPlayerView) view).changeVideoSize(false);
                }
            }

            @Override
            public void OnZoomedIn(View view) {
                Log.d(TAG, "video zoom in");
                if (view instanceof VideoPlayerView) {
                    ((VideoPlayerView) view).changeVideoSize(true);
                }
            }
        });

        contentPager_flyt.getViewTreeObserver().addOnGlobalFocusChangeListener(new OnGlobalFocusChangeListener() {

            @Override
            public void onGlobalFocusChanged(View oldFocus, View newFocus) {
                focusAmplifier.notifyFocusChanged(newFocus, true);
            }
        });
        doHttpGetViewPageData();
        return view;

    }

    /*
     * (non-Javadoc)
     * 
     * @see android.support.v4.app.Fragment#onActivityCreated(android.os.Bundle)
     */
    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        // TODO 当父activity的onCreate()执行完成后调用
        Log.d(TAG, "onActivityCreate()");
    }

    /*
     * (non-Javadoc)
     * 
     * @see android.app.Fragment#onStart()
     */
    @Override
    public void onStart() {
        super.onStart();
        Log.d(TAG, "OnStart()");
    }

    /*
     * (non-Javadoc)
     * 
     * @see android.app.Fragment#onResume()
     */
    @Override
    public void onResume() {
        super.onResume();
        Log.d(TAG, "OnResume()");

        View page = contentPager_flyt.getPageByIndex(contentPager_flyt.getIndex());
        ArrayList<VideoPlayerView> videoViews = VideoPlayerView.getInstanceTags();
        if (videoViews != null) {
            for (VideoPlayerView videView : videoViews) {
                if (page == videView.getParent()) {
                    videView.play();
                }
            }
        }
    }

    /*
     * (non-Javadoc)
     * 
     * @see android.app.Fragment#onPause()
     */
    @Override
    public void onPause() {
        super.onPause();
        Log.d(TAG, "OnPause()");

        ArrayList<View> subPages = contentPager_flyt.getPages();
        ArrayList<VideoPlayerView> videoViews = VideoPlayerView.getInstanceTags();
        if (subPages != null && subPages.size() > 0 && videoViews != null && videoViews.size() > 0) {
            for (View page : subPages) {
                for (VideoPlayerView videView : videoViews) {
                    if (page == videView.getParent()) { // current page's view
                        videView.stop();
                        videView.relase();
                    }
                }
            }
        }
    }

    /*
     * (non-Javadoc)
     * 
     * @see android.app.Fragment#onStop()
     */
    @Override
    public void onStop() {
        super.onStop();

        Log.d(TAG, "OnStop()");
    }

    /*
     * (non-Javadoc)
     * 
     * @see android.support.v4.app.Fragment#onDestroyView()
     */
    @Override
    public void onDestroyView() {
        Log.d(TAG, "OnDestroyView()");

        // TODO 当消失到后台，进入堆栈时的回调
        // 清除资源相关views
        super.onDestroyView();
    }

    /*
     * (non-Javadoc)
     * 
     * @see android.support.v4.app.Fragment#onDestroy()
     */
    @Override
    public void onDestroy() {
        Log.d(TAG, "OnDestroy()");
        threadPool.shutdownNow();
        mutex = null;
        // TODO 当该Fragment销毁时的回调
        // 清除所有资源，包括后台执行线程，关闭数据库等
        super.onDestroy();
    }

    /*
     * (non-Javadoc)
     * 
     * @see android.support.v4.app.Fragment#onDetach()
     */
    @Override
    public void onDetach() {
        Log.d(TAG, "OnDetach()");
        // TODO 当该fragment 从activity上分离时，回调
        super.onDetach();
    }

    private void doHttpGetViewPageData() {
        threadPool.execute(new LoadJsonDataRunnable());
    }

    private class LoadJsonDataRunnable implements Runnable {

        private static final int RECOMMENDED_FILE = 5;

        public LoadJsonDataRunnable() {}

        @Override
        public void run() {
            XHttpClient client = XHttpClient.getInstance();
            XHttpParamsUtil paramsUtil = XHttpParamsUtil.getInstance();
            JsonParseUtil parseUtil = JsonParseUtil.getInstance();

            String json = null;
            try {
                // XHttpParams params = new XHttpParams();
                // params.addAC(HttpComParams.AC.INDEX);
                // params.addFUNC(HttpComParams.FUNC.INDEX);
                //
                // params.addQueryStringParam(HttpComParams.KEY.CLIENT_TYPE,
                // ComParams.CLIENT_TYPE);
                //
                // params.addQueryStringParam(HttpComParams.KEY.PCODE, ComParams.PCODE);
                // params.addQueryStringParam("lan", "1");
                // params.addQueryStringParam("token", "123456");
                // params.addQueryStringParam("path", "100251660/4194_100251660_utf8.inc");
                // params.addQueryStringParam("type", "cpsPath");
                // params.addQueryStringParam("isdebug", "1");
                ResponseInfo<String> res = client.getSync("http://211.149.200.227:30104/info.php?type=recommended&ggg="
                        + new Random().nextInt(10000000), null, null);// (params.toXRequestParams(),
                // null);
                Log.i(TAG, res.result);
                BaseEntity<JsonArray> jsonResult = parseUtil.getIndex(res.result);
                switch (jsonResult.getCode()) {
                case 0:
                    json = jsonResult.getInfo().toString();
                }
            } catch (HttpException e) {
                e.printStackTrace();
            } catch (NullPointerException e) {
                e.printStackTrace();
            } catch (JsonSyntaxException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
            handleViewPageByJsonData(json);
        }
    }

    /**
     * 数据缓存 处理
     * 
     * @param json
     */
    private void handleViewPageByJsonData(String json) {
        JsonArray contentData = null;
        try {
            if (!TextUtils.isEmpty(json)) {
                contentData = JsonParseUtil.getInstance().parseHomeContent(json);
                // save success data to local cache file
                FileAccess.writeDataToFile(_activity, AppTest.TEST_ASSET_FNAME_HOME_VIEW_PAGER, json);
            }
        } catch (JsonSyntaxException e) {
            e.printStackTrace();
        } catch (NullPointerException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (contentData == null) {
            // get previous data
            json = FileAccess.getFileData(_activity, AppTest.TEST_ASSET_FNAME_HOME_VIEW_PAGER);
            // previous is empty use asset resource
            if (TextUtils.isEmpty(json)) {
                json = FileAccess.getTestDataFromAssets(LauncherApplication.getInstance(),
                        AppTest.TEST_ASSET_FNAME_HOME_VIEW_PAGER);
            }
            try {
                contentData = JsonParseUtil.getInstance().parseHomeContent(json);
            } catch (JsonSyntaxException e) {
                e.printStackTrace();
            } catch (NullPointerException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        generateViewPageByJsonData(contentData);
    }

    private void generateOnePage(JsonElement jsonElement) {
        try {
            mutex.acquire();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (NullPointerException e) {
            e.printStackTrace();
            return;
        }
        uIGenerator.parseSource((JsonArray) jsonElement);
        hander.post(new Runnable() {
            @Override
            public void run() {
                try {
                    if (getActivity().isFinishing())
                        return;
                    View view = uIGenerator.generateView();
                    view.setDrawingCacheEnabled(true);
                    addANewPage(view);
                    mutex.release();
                } catch (NullPointerException e) {
                    e.printStackTrace();
                    return;
                }
            }
        });
    }

    private void generateViewPageByJsonData(JsonArray contentData) {
        if (contentData != null) {
            for (JsonElement jsonElement : contentData) {
                generateOnePage(jsonElement);
            }
            hander.post(new Runnable() {
                @Override
                public void run() {
                    if (getActivity() == null || getActivity().isFinishing())
                        return;
                    int pageIndex = 0;
                    View focus = null;
                    try {
                        for (int i = 0; i < contentPager_flyt.getPageCount(); i++) {
                            View v = contentPager_flyt.getPageByIndex(i);
                            if (!(v instanceof ViewGroup))
                                continue;
                            ViewGroup vg = (ViewGroup) v;
                            for (int j = 0; j < vg.getChildCount(); j++) {
                                View child = vg.getChildAt(j);
                                if (!(child.getTag() instanceof Attributes))
                                    continue;
                                Attributes attrs = (Attributes) child.getTag();
                                if (attrs.getBoolean(AttributeKey.FOCUS, false)) {
                                    pageIndex = i;
                                    focus = child;
                                    break;
                                }
                            }
                            if (focus != null)
                                break;
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    contentPager_flyt.setIndex(pageIndex);
                    if (focus != null)
                        focus.requestFocus();
                }
            });
        }

    }

    /**
     * 添加page ,添加 Point 指示器
     */
    private void addANewPage(View view) {
        if (view != null) {
            contentPager_flyt.addPage(view);
            pagePointer.addNewPoints(_activity, 1);
            pagePointer.setPosition(contentPager_flyt.getIndex());
        }
    }

    Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            startScrollMessage();
        }

    };

    private void startScrollMessage() {
        final UserInfo userInfo = UserInfoKeeper.getInstance().getInfo();
        // if (userInfo == null || TextUtils.isEmpty(userInfo.getToken()))
        // return;

        new TmsGetFileTask(new onTmsGetFile() {
            @Override
            public void onTaskToResult(BaseEntity<FileInfo> baseEntity) {
                String uriPath = null;
                try {
                    uriPath = baseEntity.getInfo().getUrl();
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    uriPath = (uriPath == null ? ComParams.SCOLL_MSG_PATH : uriPath);
                }
                // RequestParams requestParams = XHttpParamsUtil.getInstance().getIndex("33333", uriPath);
                RequestParams requestParams = null;
                XHttpClient.getInstance().get("http://211.149.200.227:30104/info.php?type=notice", requestParams,
                        new RequestCallBack<String>() {
                            @Override
                            public void onStart() {
                                Log.i(TAG, "dddd  ---  url = " + this.getRequestUrl());

                            }

                            @Override
                            public void onFailure(HttpException arg0, String arg1) {}

                            @Override
                            public void onSuccess(ResponseInfo<String> arg0) {
                                try {
                                    if (getActivity().isFinishing())
                                        return;
                                    Log.i(TAG, arg0.result);
                                    BaseEntity<MarqueeMsgInfo> info = JsonParseUtil.getInstance().getMarqueeMsg(
                                            arg0.result);
                                    switch (info.getCode()) {
                                    case 0:
                                        MarqueeMsgInfo msg = info.getInfo();
                                        marqueeText.setSpeed(msg.getDuration());
                                        marqueeText.setRepeatTime(msg.getTimes());
                                        marqueeText.setPearDelayTime(msg.getPeriod());
                                        String msgStr = URLDecoder.decode(msg.getMessage(), "UTF-8");
                                        marqueeText.setText(msgStr);
                                        marqueeText.start();
                                        handler.sendEmptyMessageDelayed(1, 30000);
                                    }
                                } catch (JsonSyntaxException e) {
                                    e.printStackTrace();
                                } catch (NullPointerException e) {
                                    e.printStackTrace();
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                        });
            }
        }).execute(String.valueOf(SCROLL_MSG_FILE));
    }
}
